package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.GridLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessExpert;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ExpertNewVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.RecommendExpertHolder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hedgehog.ratingbar.RatingBar;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import org.sufficientlysecure.htmltextview.HtmlTextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2017/2/6 14:57
 * 修改备注：
 * ================================================
 */

public class AgriculturalExpertsDetailsActivity extends BaseActivity {

    @Bind(R.id.expert_details_iv_expert_avatar)
    SimpleDraweeView expertDetailsIvExpertAvatar;
    @Bind(R.id.expert_details_tv_expert_titles)
    TextView expertDetailsTvExpertTitles;
    @Bind(R.id.expert_details_tv_expert_name)
    TextView expertDetailsTvExpertName;
    @Bind(R.id.expert_details_tv_research_direction)
    HtmlTextView expertDetailsTvResearchDirection;
    @Bind(R.id.expert_details_tv_research_result)
    HtmlTextView expertDetailsTvResearchResult;
    @Bind(R.id.expert_details_recyclerView)
    EasyRecyclerView expertDetailsRecyclerView;
    @Bind(R.id.expert_details_ratingbar)
    RatingBar expertDetailsRatingbar;
    @Bind(R.id.expert_details_consultation)
    TextView ivConsultation;

    private List<ExpertNewVO> expertVOList = new ArrayList<>();
    private RecyclerArrayAdapter adapter;
    private OptionsPickerView pvOptions;
    private ExpertNewVO expertVO;

//    private List<QuestionTypeVO.ResearchFieldTwoStagesBean> expertTypeVOList = new ArrayList<>();
//    private List<List<QuestionTypeVO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean>> listList = new ArrayList<>(); // 二级菜单

    Map<String, Object> map = new HashMap<>();

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_agricultural_experts_details);
        setTitle("专家详情");
    }

    @Override
    public void initMember() {

        adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new RecommendExpertHolder(parent);
            }
        };

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        expertDetailsRecyclerView.setLayoutManager(gridLayoutManager);
        expertDetailsRecyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));
        expertDetailsRecyclerView.setAdapterWithProgress(adapter);


        map = (Map<String, Object>) getIntent().getSerializableExtra("map");

//        expertTypeVOList = (List<QuestionTypeVO.ResearchFieldTwoStagesBean>) map.get("expertTypeVOList");
//        listList = (List<List<QuestionTypeVO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean>>) map.get("listList");
//
//        if (expertTypeVOList != null && listList != null && expertTypeVOList.size() > 0 && listList.size() > 0)
//            initOptionPicker();
        if (map == null) {
            // 调用专家详情接口 获取推荐列表
            BusinessExpert.getExpertDetails(this, (String) getIntent().getSerializableExtra("id"), mHandler);
            return;
        }

        expertVO = (ExpertNewVO) map.get("ExpertVO");
        // 调用专家详情接口 获取推荐列表
        BusinessExpert.getExpertDetails(this, expertVO.getId(), mHandler);
        setView(expertVO);


    }

    private void setView(ExpertNewVO expertVO) {

        if (expertVO == null)
            return;

        // 头像
        FrescoUtil.showImageSmall(expertVO.getPhoto() != null ? expertVO.getPhoto() : "", expertDetailsIvExpertAvatar);
        // 职位 title
        if (expertVO.getExpertTitle() != null) {
            expertDetailsTvExpertTitles.setText(expertVO.getExpertTitle().getTitle());
        } else
            expertDetailsTvExpertTitles.setVisibility(View.INVISIBLE);

        // 专家姓名
        expertDetailsTvExpertName.setText(expertVO.getExpertName());
        // 研究方向
        if (expertVO.getExpertAreas() != null) {
            String s = "";
            for (int i = 0; i < expertVO.getExpertAreas().size(); i++) {
                s += expertVO.getExpertAreas().get(i).getExpertAreaType().getName() + "-" + expertVO.getExpertAreas().get(i).getExpertAreaDirection().getName() + "\n";
            }
            expertDetailsTvResearchDirection.setHtml(s);
        }
        // 研究成果
        expertDetailsTvResearchResult.setHtml(expertVO.getExpertIntroduce() != null ? expertVO.getExpertIntroduce() : "");
        // 评价
        expertDetailsRatingbar.setStar((float) expertVO.getScore());
    }

    private String calculateAge(String birthday) {
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
            int age = (new Date().getYear() - date.getYear());
            return String.valueOf(age) + "岁";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "保密";
    }

    @Override
    public void addListener() {

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Map<String, Object> map = new HashMap<>();
                map.put("ExpertVO", adapter.getAllData().get(position));
                GotoUtil.gotoActivity(AgriculturalExpertsDetailsActivity.this, AgriculturalExpertsDetailsActivity.class, true, "map", map);
            }
        });

        ivConsultation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Utils.isLogin(AgriculturalExpertsDetailsActivity.this)) {
                    startActivityForResult(new Intent(AgriculturalExpertsDetailsActivity.this, LoginActivity.class), 1);
                    return;
                }

                if (expertVO == null)
                    return;
                GotoUtil.gotoActivity(AgriculturalExpertsDetailsActivity.this, ConsultIssueV2Activity.class, "single", expertVO);
//                if (pvOptions != null) {
//                    pvOptions.show();
//                } else {
//                    showToast("正在获取专家类型");
//                    BusinessExpert.getExpertTypeList(AgriculturalExpertsDetailsActivity.this, mHandler);
//                }
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_GET_EXPERT_DETAILS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_EXPERT_TYPE_LIST_SUCCESS: // 专家分类 <侧边栏>
//                        expertTypeVOList = FastJsonUtil.getListBean(msg.obj.toString(), "body", "industryTypes", QuestionTypeVO.ResearchFieldTwoStagesBean.class);
//
//                        if (expertTypeVOList == null || expertTypeVOList.size() == 0)
//                            return;
//
//                        for (int i = 0; i < expertTypeVOList.size(); i++) {
//                            listList.add(expertTypeVOList.get(i).getResearchFieldThreeStageVos());
//
//                        }
//                        initOptionPicker();
//                        pvOptions.show();
                        break;
                }
            }
        };
    }


    private void initOptionPicker() {//条件选择器初始化
//        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int option2, int options3, View v) {
//                //返回的分别是三个级别的选中位置
//                if (null == expertTypeVOList || expertTypeVOList.size() <= 0)
//                    return;
//                QuestionTypeVO.ResearchFieldTwoStagesBean typeVO = expertTypeVOList.get(options1);
//                QuestionTypeVO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean listBean = listList.get(options1).get(option2);
//                Map<String, Object> map = new HashMap<>();
//                map.put("typeVO", typeVO);
//                map.put("listBean", listBean);
//                GotoUtil.gotoActivity(AgriculturalExpertsDetailsActivity.this, ConsultIssueV2Activity.class, "map", map);
//            }
//        })
//                .setSubmitText("下一步")
//                .setCancelText("取消")
//                .setTitleText("咨询分类")
//                .setSubCalSize(16)//确定取消按钮大小
//                .setLineSpacingMultiplier(1.7f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
//                .setDividerColor(getResources().getColor(R.color.app_color))//设置分割线的颜色
//                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
//                .setContentTextSize(18)//设置滚轮文字大小
//                .setSelectOptions(0, 0)  //设置默认选中项
//                .build();
//
//        pvOptions.setPicker(expertTypeVOList, listList);

    }

    @Override
    public void callBack(Object object) {
        expertVOList = FastJsonUtil.getListBean(object.toString(), "body", "expertList", ExpertNewVO.class);
        expertVO = FastJsonUtil.getBean(object.toString(), "body", "expert", ExpertNewVO.class);
        setView(expertVO);
        adapter.clear();
        adapter.addAll(expertVOList);
    }

    @Override
    public void rightOnClick() {
//        if (!Utils.isLogin(this)) {
//            startActivityForResult(new Intent(this, LoginActivity.class), 1);
//            return;
//        }
//        if (pvOptions != null) {
//            pvOptions.show();
//        } else {
//            showToast("正在获取专家类型");
//            BusinessExpert.getExpertTypeList(this, mHandler);
//        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (pvOptions != null && pvOptions.isShowing()) {
            pvOptions.dismiss();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
